import json
import time

from flask import jsonify, request, Response
from redis import Redis

from myApp.model.build_model import BuildInfo
from myApp.model.message_model import Message

from myApp.model.room_model import Room
from flask import Blueprint

from myApp.utils.BuildModel import build_model
# from myApp.utils.FuZiModel import run_fuzi
from myApp.utils.ChatGlmModel import run_glm
from myApp.utils.CaseModel import case_model

message_db = Blueprint('message', __name__)
# redis_client = Redis(host='10.206.60.14', port=6379, db=0, decode_responses=True)
redis_client = Redis(host='127.0.0.1', port=6379, db=0, decode_responses=True, password='vsoft@123&')


def submit_user_data(data):
    message = Message()
    message.user_id = data.get('user_id')
    message.text = data.get('text', None)
    message.room_id = data.get('room_id', None)
    message.role = 'user'
    message.model = data.get('model')
    message.id = data.get('id')

    # new_room = data.get('new_room', None)

    if message.text is None:
        return jsonify({'message': '内容为空'}), 201

    # 创建房间 + 更新房间时间
    Room.create_room(data.get('room_id'), data.get('text'), data.get('user_id'))
    # 更新房间时间（仅在用户发送时更新）
    # Room.update_room_update_time(data.get('room_id'))

    # 1. 插入用户消息
    Message.create_message(id=message.id, user_id=message.user_id, text=message.text, room_id=message.room_id,
                           role=message.role,
                           model=message.model)


@message_db.route('/stream', methods=['POST'])
def stream():
    data = request.get_json()
    # 重新回答的标记
    refresh = data.get('refresh')
    if not refresh:
        submit_user_data(data)

    user_text = data.get('text')
    model_name = data.get('model')
    model_suffix = data.get('suffix')
    assistant_message_id = data.get('assistantMessageId')

    if model_name == "inference":
        return ""
        # return Response(run_fuzi(model_suffix, user_text, assistant_message_id, []), content_type='text/event-stream')
    elif model_name == "common":
        # return ""
        return Response(run_glm(user_text, assistant_message_id), content_type='text/event-stream')
    elif model_name == "caseModel":
        # return ""
        return Response(case_model(user_text, assistant_message_id),
                        content_type='text/event-stream')
    elif model_name == "buildModel":
        # return ""
        return Response(build_model(user_text, assistant_message_id),
                        content_type='text/event-stream')




@message_db.route('/message/stop', methods=['POST'])
def set_key_value():
    data = request.get_json()
    assistant_message_id = data.get('assistantMessageId')
    redis_client.set(assistant_message_id, "end")
    redis_client.expire(assistant_message_id, 600)
    return {'message': 'success'}, 200


@message_db.route('/message/add', methods=['POST'])
def message_add():
    data = request.get_json()

    message = Message()
    message.user_id = data.get('user_id')
    message.text = data.get('text', None)
    message.room_id = data.get('room_id', None)
    message.model = data.get('model')
    # message.id = data.get('id')
    # 重新回答的标记
    refresh = data.get('refresh')

    message.role = 'assistant'

    # 前端生成的AI消息id
    assistantMessageId = data.get('assistantMessageId')

    if refresh:  # 重新回答，刷新原有的消息
        Message.update_message(id=assistantMessageId, text=message.text, model=message.model)
    else:
        Message.create_message(id=assistantMessageId, user_id=message.user_id, text=message.text,
                               room_id=message.room_id,
                               role=message.role,
                               model=message.model)

    return jsonify({'message': "success"}), 200


# message：user_id、text、room_id、role、model
@message_db.route('/chat', methods=['POST'])
def chat():
    data = request.get_json()

    message = Message()
    message.user_id = data.get('user_id')
    message.text = data.get('text', None)
    message.room_id = data.get('room_id', None)
    message.role = 'user'
    message.model = data.get('model')
    message.id = data.get('id')
    # 重新回答的标记
    refresh = data.get('refresh')
    # new_room = data.get('new_room', None)

    if message.text is None:
        return jsonify({'message': '内容为空'}), 201

    # 创建房间 + 更新房间时间
    isNew = Room.create_room(data.get('room_id'), data.get('text'), data.get('user_id'))
    # 更新房间时间（仅在用户发送时更新）
    # Room.update_room_update_time(data.get('room_id'))

    # 1. 插入用户消息
    if not refresh:
        Message.create_message(id=message.id, user_id=message.user_id, text=message.text, room_id=message.room_id,
                               role=message.role,
                               model=message.model)

    # 2. 调用模型，进行对话
    history = data.get('history')
    response = f"AI回答：{data.get('assistantMessageId')}"
    # response, updated_history = run(mod, history, msg)

    time.sleep(1)
    # 3. 插入模型消息
    message.text = response
    message.role = 'assistant'

    # 前端生成的AI消息id
    assistantMessageId = data.get('assistantMessageId')

    if refresh:  # 重新回答，刷新原有的消息
        Message.update_message(id=assistantMessageId, text=message.text, model=message.model)
    else:
        Message.create_message(assistantMessageId, user_id=message.user_id, text=message.text,
                               room_id=message.room_id,
                               role=message.role,
                               model=message.model)

    return jsonify({'assistant': response, 'isNew': isNew}), 200


# 根据用户和房间获取消息
@message_db.route('/messages/list', methods=['POST'])
def get_all_messages():
    data = request.json
    room_id = data.get('room_id')
    messages = Message.get_messages_by_room(room_id)
    print([message.serialize() for message in messages])
    return jsonify({'data': [message.serialize() for message in messages]}), 200


@message_db.route('/messages/delete', methods=['POST'])
def delete_message():
    data = request.json
    Message.delete_message_by_room_id(data.get('room_id'))
    return jsonify({'message': 'success'}), 200

# 获取消息列表，根据page、size
# @message_db.route('/messages/page', methods=['POST'])
# def get_messages():
#     data = request.json
#     message_param = Message()
#     message_param.user_id = data.get('user_id']
#     message_param.room_id = data.get('room_id']
#     message_param.status = 1
#     message_param.role = data.get('role']
#     message_param.model = data.get('model']tyyw20
#
#     page = data.get('page']
#     size = data.get('size']
#
#     messages = Message.get_messages_by_page(page, size, message_param)
#     return jsonify([message.serialize() for message in messages.items]), 200
